import type { DownloadParam } from "@common/http-service-types";
import { exposeGlobal } from "@/framework/util/dev-helper";

export interface HttpResponse<T> {
  data: T;
}

export function requestGet<T = any>(url: string, query?: Record<string, any>): Promise<HttpResponse<T>> {
  return ipc.invoke("http:get", query != null ? addQuery2Url(url, object2query(query)) : url, "json");
}

export function requestGetText(url: string, query?: Record<string, any>): Promise<HttpResponse<string>> {
  return ipc.invoke("http:get", query != null ? addQuery2Url(url, object2query(query)) : url, "text");
}

export function requestPost<T = any>(url: string, body: Record<string, any>): Promise<HttpResponse<T>> {
  return ipc.invoke("http:post", url, body);
}

exposeGlobal("_get", requestGet);
exposeGlobal("_getText", requestGetText);
exposeGlobal("_post", requestPost);

export function object2query(obj: Record<string, string | number | boolean | null | undefined>) {
  return Object.keys(obj)
    .map(key => {
      let value = obj[key];
      if (Array.isArray(value)) {
        value = value.join(",");
      }
      return `${key}=${value == null ? "" : encodeURIComponent(value)}`;
    })
    .join("&");
}

function addQuery2Url(url: string, query: string) {
  if (query == null || query.trim().length === 0) {
    return url;
  }
  const connector = url.indexOf("?") === -1 ? "?" : "&";
  return url + connector + query;
}

/**
 * 下载文件
 */
export function downloadFile(param: DownloadParam) {
  ipc.send("http:download", param);
}
